import React, {Component} from 'react';
import {Image, StyleSheet, Text, TouchableOpacity, View} from 'M/UI/Libraries';
import PhoneCaptcha from 'WE/UI/Components/PhoneCaptcha';
import {userService} from 'WE/Services';
import captchaAppImage from 'WE/Resource/icon/captcha_app.png';
import {Alert, Linking} from 'react-native';
import {buildSign, getUrlParams} from 'WE/Utils';
import {globalService} from 'M/Services';

const phone = '12800128000';
const merchantId = 'UShY8olLfrhogAOM';
const appName = 'weskinny';
const key = 'Uo12kx8DK5NwiwjawJGC8TFAP6WBT1d8';
export default class PhoneLogin extends Component {
  state = {
    captcha: '',
  };

  componentDidMount() {
    this.subscription = globalService.addLinkingEventListener(this.linkEvent);
  }

  linkEvent(url) {
    if (url) {
      console.log('linkEvent', url);
      let urlParams = getUrlParams(url);
      const {openId} = urlParams;
      if (!openId) {
        Alert.alert('后台中获取的授权数据', JSON.stringify(urlParams));
        return;
      }
      const p = {
        path: '/third-party-merchant/auth-data',
        params: {
          sign: buildSign({
            data: {merchantId, appName, openId},
            appKey: key,
          }),
          merchantId,
          appName,
          openId: decodeURI(openId),
        },
      };
      smsRequest.get(p).then(ds => {
        Alert.alert('后台中获取的授权数据', JSON.stringify(ds));
      });
    }
  }

  componentWillUnmount() {
    this.subscription.remove();
  }

  onSetName = ({name}) => this.setState({...this.state, name});
  onSetCode = ({code}) => this.setState({...this.state, captcha: code});
  onOAuthLogin = async () => {
    const appDeepLink = 'wscaptcha://we.skinny.captcha';
    if (!(await Linking.canOpenURL(appDeepLink))) {
      const url = `${appDeepLink}?appName=weskinny&merchantId=${merchantId}&type=oauth&callbackDeeplink=weskinny://we.skinny`;
      let value = await Linking.openURL(url);
      console.log('value', value);
    }
  };
  onLogin = async () => {
    const {captcha, phone, name} = this.state;
    try {
      await userService.login({captcha, phone, name});
      this.props.navigation.navigate('Home');
    } catch ({message}) {
      if (message) {
        globalService.getToast().show(message);
      }
    }
  };

  onSendCaptcha = async phone => {
    try {
      const {
        showUserName = false,
        showMaskName = false,
        maskNames,
        captcha = '',
      } = await userService.sendCaptchaSms({phone});
      this.setState({showUserName, showMaskName, maskNames, captcha, phone});
      globalService.getToast().show('发送成功。');
    } catch (e) {
      console.error(e);
    }
    return false;
  };

  render() {
    const {captcha, showUserName, showMaskName, maskNames} = this.state;
    return (
      <View style={styles.container}>
        <PhoneCaptcha
          value={captcha}
          showName={showUserName}
          onChange
          onSetName={this.onSetName}
          onSetCode={this.onSetCode}
          onSendCaptcha={this.onSendCaptcha}
          phone={phone}
        />

        {showMaskName
          ? maskNames.map((maskName, index) => (
              <View key={'v' + index} style={styles.maskNameList}>
                <Text>{maskName}</Text>
              </View>
            ))
          : null}

        <View style={[{marginTop: 30}]}>
          <TouchableOpacity onPress={this.onLogin}>
            <Text style={styles.loginTypeText}>注册/登录</Text>
          </TouchableOpacity>
        </View>
        <View style={[{marginTop: 30}]}>
          <TouchableOpacity onPress={this.onOAuthLogin}>
            <Image
              style={[{width: 60, height: 60, marginLeft: 165}]}
              source={captchaAppImage}
            />
            <Text style={styles.loginTypeText}>验证码App 授权登陆</Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {flex: 1},
  maskNameList: {
    padding: 10,
    letterSpacing: 3,
    fontSize: 18,
  },
  themeStyle: {
    primaryColor: '#01987B',
    minorFontColor: '#9BA7B2',
  },
  username: {
    paddingTop: 30,
    padding: 10,
  },
  loginTypeText: {
    fontSize: 18,
    color: '#333333',
    textAlign: 'center',
    lineHeight: 17,
    paddingVertical: 15,
  },
});
